import geopandas as gpd
import pandas as pd
from bpy.types import Operator
import bmesh
import bpy
import math
import numpy
import sys
from mathutils import Vector, Matrix, noise, Quaternion
sys.path.extend(['', 'D:\\blender-2.92.0-windows64\\2.92\\python\\bin\\python37.zip', 'D:\\blender-2.92.0-windows64\\2.92\\python\\DLLs', 'D:\\blender-2.92.0-windows64\\2.92\\python\\lib', 'D:\\blender-2.92.0-windows64\\2.92\\python\\bin',
                'C:\\Users\\tomye\\AppData\\Roaming\\Python\\Python37\\site-packages', 'D:\\blender-2.92.0-windows64\\2.92\\python', 'D:\\blender-2.92.0-windows64\\2.92\\python\\lib\\site-packages'])

def makeSpline(cu, typ, points):
    spline = cu.splines.new(typ)
    npoints = len(points)
    spline.points.add(npoints-1)    # One point already exists?
    for (n, pt) in enumerate(points):
        spline.points[n].co = pt

    return


def curve_to_mesh(context, curve):
    deg = context.evaluated_depsgraph_get()
    me = bpy.data.meshes.new_from_object(
        curve.evaluated_get(deg), depsgraph=deg)

    # 创建mesh实体
    # new_obj = bpy.data.objects.new(curve.name + "_mesh", me)
    # context.collection.objects.link(new_obj)
    # for o in context.selected_objects:
    #     o.select_set(False)
    # new_obj.matrix_world = curve.matrix_world

    return me


def draw_smooth_pipe(pipeName, pipeData, diameter,obj):
    cu = bpy.data.curves.new(name="MyCurve", type="CURVE")
    ob = bpy.data.objects.new(pipeName, cu)
    bpy.context.scene.collection.objects.link(ob)
    ob.data.bevel_mode = 'OBJECT'
    ob.data.bevel_object = obj
    # ob.data.bevel_depth = diameter
    #ob.data.use_fill_caps = False

    cu.dimensions = "3D"
    makeSpline(cu, "NURBS", pipeData)
    me = curve_to_mesh(bpy.context, ob)

    # 删除曲线实体
    ob.select_set(True)
    bpy.ops.object.delete(use_global=False)

    return me


class Draw_Triangle_Op(Operator):
    bl_idname = "object.draw_triangle"
    bl_label = "draw triangle"
    bl_description = "draw a triangle"
    
    def execute(self,context):
        data = gpd.read_file(r"C:\Users\tomye\Documents\中线.geojson")
        offsetX = data.geometry[0].centroid.x
        offsetY = data.geometry[0].centroid.y
        offsetZ = 0.0
        print(data.geometry.centroid)
        names = []

        
        # create the material
        new_mat = bpy.data.materials.new(name="myMaterial")

        new_mat.use_nodes = True
        nodes = new_mat.node_tree.nodes
        material_output = nodes.get("Material Output")
        node_checker_texture = nodes.new(type="ShaderNodeTexChecker")
        
        node_checker_texture.inputs[1].default_value = (0.0596932, 0.0718455, 0.8, 1)
        node_checker_texture.inputs[2].default_value = (0.0204486, 0.2, 0.0251988, 1)

        links = new_mat.node_tree.links
        new_link = links.new(node_checker_texture.outputs[0],material_output.inputs[0])
        
        datas=[]
        diameter =1.0 
        for index, row in data.iterrows():
            name = row['管道编码']
            x1 = row.geometry.coords.xy[0][0]-offsetX
            y1 = row.geometry.coords.xy[1][0]-offsetY
            z1 = row['起点高程']
            x2 = row.geometry.coords.xy[0][1]-offsetX
            y2 = row.geometry.coords.xy[1][1]-offsetY
            z2 = row['终点高程']
            if name in names:
                print(name + "已经存在")
            else:
                names.append(name)
                datas.append((x1, y1, z1, 1))

        verts = [(0.1,0,0),(0.1,1,0),(-0.1,1,0),(-0.1,0,0)]
        lines = [(0,1),(1,2),(2,3),(3,0)]
        # Create Mesh Datablock
        mesh = bpy.data.meshes.new('me')
        mesh.from_pydata(verts, lines, [])

        # Create Object and link to scene
        obj = bpy.data.objects.new('me1', mesh)
        bpy.context.scene.collection.objects.link(obj)

        bpy.context.view_layer.objects.active = obj
        obj.select_set(True)
        bpy.ops.object.convert(target='CURVE')

        mesh = draw_smooth_pipe(
            'mesh', datas, diameter,obj)  # 返回管线的mesh
        obj = bpy.data.objects.new('center_pipe', mesh)
        bpy.context.scene.collection.objects.link(obj)
        # obj.data.materials.append(new_mat)
        
        print(offsetX)
        print(offsetY)
        return {'FINISHED'}